package com.association.main.frontcontroller;

import com.association.main.common.R;
import com.association.main.domain.Clubs;
import com.association.main.domain.MailRequest;
import com.association.main.domain.Members;
import com.association.main.domain.Users;
import com.association.main.service.MailService;
import com.association.main.service.MembersService;
import com.association.main.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/front")
public class LoginController {

    @Value("${title}")
    private String title;


    private final Cache<String, String> emailCodeCache = Caffeine.newBuilder()
            .expireAfterWrite(3, TimeUnit.MINUTES) // 设置过期时间为10分钟
            .build();

    @Autowired
    private MailService mailService;
    @Autowired
    private MembersService membersService;
    @PostMapping("/login")
    public R<Map> login(@RequestBody Members members){
        //1.查询用户是否存在
        LambdaQueryWrapper<Members> membersLambdaQueryWrapper=new LambdaQueryWrapper<>();
        membersLambdaQueryWrapper.eq(Members::getUsername,members.getUsername());
        membersLambdaQueryWrapper.eq(Members::getPassword,members.getPassword());
        Members members1 = membersService.getOne(membersLambdaQueryWrapper);
        if(members1!=null){ //则说明登录成功
            Users users=new Users();
            users.setId(members1.getId());
            users.setRole("0");//无使用
            users.setUsername(members1.getUsername());
            String jwtToken = JwtUtil.getJwtToken(users);
            long expirationTime = JwtUtil.getTokenExpirationTime(jwtToken)/1000;
            Map map=new HashMap();
            //存用户基本信息和token
            map.put("myToken",jwtToken);//与后台区分，加大安全边界
            map.put("id",members1.getId());
            map.put("username",members1.getUsername());
            map.put("realname",members1.getName());
            map.put("exp",expirationTime);
            return R.success(map);
        }else{
            return R.error("账号或密码错误");
        }
    }

    //通过token获取用户角色
    @GetMapping("/userInfo")
    public R<Map> loginrole(HttpServletRequest request){
        String token = request.getHeader("token");
        //通过接受到的token获取角色
        String userType = JwtUtil.getUserType(token);
        Integer userId = JwtUtil.getUserId(token);
        Members members = membersService.getById(userId);
        Map map=new HashMap();
        String[] role=new String[1];
        role[0]=userType;
        map.put("email",members.getEmail());
        map.put("phone",members.getPhone());
        map.put("name",members.getName());
        map.put("sex",members.getSex());
        map.put("username",members.getUsername());
        map.put("avater",members.getAvater());
        map.put("createdAt",members.getCreatedAt());
        return R.success(map);
    }

    @PostMapping("/usereditor")
    public R<String> usereditor(String phone,String oldPassword, String newPassword,HttpServletRequest request){
        log.info(oldPassword+"||"+newPassword);
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);
        //先查询老密码是否正确
        LambdaQueryWrapper<Members> membersLambdaQueryWrapper=new LambdaQueryWrapper<>();
        membersLambdaQueryWrapper.eq(Members::getId,userId);
        membersLambdaQueryWrapper.eq(Members::getPassword,oldPassword);
        Members one = membersService.getOne(membersLambdaQueryWrapper);
        if(one!=null){
            //说明老密码是正确的可以进行下一步操作
            LambdaUpdateWrapper<Members> membersLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
            membersLambdaUpdateWrapper.set(Members::getPhone,phone);
            membersLambdaUpdateWrapper.set(newPassword!=null,Members::getPassword,newPassword);
            membersLambdaUpdateWrapper.eq(Members::getId,userId);
            boolean update = membersService.update(membersLambdaUpdateWrapper);
            if(update ==true){
              return   R.success("修改资料成功！");
            }
        }
        return R.error("旧密码错误");
    }



    @GetMapping("/logtime")
    public R<String> logtime(HttpServletRequest request){
        String token = JwtUtil.checkToken(request);
        return R.success(token);
    }


    @PostMapping("/reg/sendVerifyCode")
    public R<String> sendVerifyCode(@RequestParam String email) {
        // 生成六位随机验证码
        String verifyCode = String.format("%06d", (int) (Math.random() * 1000000));
        MailRequest mailRequest=new MailRequest();
        mailRequest.setSubject(title+"-平台注册验证码");
        mailRequest.setText("你的注册验证码为："+verifyCode);
        mailRequest.setSendTo(email);
        boolean b = mailService.sendHtmlMail(mailRequest);
        if(b==true){
//            存入缓存
            emailCodeCache.put(email,verifyCode);
            return R.success("验证码发送成功");
        }
        return R.error("验证码发送失败");

    }
    @PostMapping("/reg/submit")
    public R<String> reg(@RequestBody Map<String,String> data){
        String username=data.get("username");
        String realname=data.get("realname");
        String sex=data.get("sex");
        String email=data.get("email");
        String phone=data.get("phone");
        String password=data.get("password");
        String emailCode=data.get("emailCode");
        String cachedCode = emailCodeCache.getIfPresent(email);
        if(emailCode.equals(cachedCode)){
            LambdaQueryWrapper<Members> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Members::getUsername,username).or().eq(Members::getEmail,email);
            Members member = membersService.getOne(lambdaQueryWrapper);
            if(member==null){
                Members members=new Members();
                members.setUsername(username);
                members.setPassword(password);
                members.setEmail(email);
                members.setPhone(phone);
                members.setSex(sex);
                members.setName(realname);
                members.setCreatedAt(LocalDateTime.now());
                membersService.save(members);
                return R.success("注册成功");
            }else{
                return R.error("用户名或邮箱已注册");
            }

            //说明邮箱验证成功
        }else{
            //失败
            return R.error("验证码错误");
        }
    }




}
